package tw.edu.tku.im.maze;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class UpdateRoomRepParser extends PacketParser {
   public static UpdateRoomRepParser INSTANCE = new UpdateRoomRepParser();
   
   private UpdateRoomRepParser() { }
   
   private static Member[] parseMembers(JSONArray jsonArray) throws JSONException {
      if(jsonArray==null){ return null; }
      Member[] ans = new Member[jsonArray.length()];
      for(int i=0; i<jsonArray.length(); i++) {
         if(jsonArray.isNull(i)) { break; }
         ans[i] = Member.parse(jsonArray.getJSONObject(i));
      }
      return ans;
   }
   
   @Override
   public UpdateRoomRep parse(JSONObject jsonObj) throws JSONException {
      JSONObject result = jsonObj.getJSONObject("result");
      boolean roomSurvive = result.getBoolean("roomSurvive");
      String roomName = result.getString("roomName");
      int mapLv = result.getInt("mapLv");
      Member[] teamOneMember;
      if(result.isNull("team1")) { teamOneMember = null; }
      else {
         JSONArray jsonTeam1 = result.getJSONArray("team1");
         teamOneMember = UpdateRoomRepParser.parseMembers(jsonTeam1);
      }
      boolean start = result.getBoolean("start");
      MazeMap map;
      if(result.isNull("map")) {
         map = null;
      } 
      else {
         map = MazeMap.parse(result.getJSONObject("map"));
      } 
      
      if(result.isNull("team2")) {
         return new UpdateRoomRep(roomSurvive, roomName, mapLv, teamOneMember, 
                                  start, map);
      }
      else {
         JSONArray jsonTeam2 = result.getJSONArray("team2");
         Member[] teamTwoMember = UpdateRoomRepParser.parseMembers(jsonTeam2);
         return new UpdateRoomRep(roomSurvive, roomName, mapLv, teamOneMember, 
                                  teamTwoMember, start, map);
      }
      
   }

   @Override
   public String acceptName() {
      return "updateRoomResponse";
   }

}
